package one.stand.util;

import one.stand.advice.ResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * @author cjr
 */
public class ResultUtil {
    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> success(T data) {
        return success(ResultEnum.IPAD_SUCCESS, data, RequestContextHolder.getRequestContext().isLogin());
    }

    public static <T> Result<T> success(T data, boolean isLogin) {
        return success(ResultEnum.IPAD_SUCCESS, data, isLogin);
    }

    public static <T> Result<T> success(ResultEnum resultEnum, T data, boolean isLogin) {
        return success(resultEnum.getCode(), resultEnum.getMessage(), data, isLogin);
    }

    public static <T> Result<T> success(int code, String message, T data, boolean isLogin) {
        return Result.<T>builder()
                .code(code)
                .message(message)
                .data(data)
                .login(isLogin)
                .build();
    }

    public static Result fail(String message) {
        return fail(ResultEnum.IPAD_FAIL.getCode(), message);
    }

    public static Result fail(ResultEnum resultEnum) {
        return fail(resultEnum.getCode(), resultEnum.getMessage());
    }

    public static Result fail(int code, String message) {
        Assert.isTrue(code > 0, "code must > 0 when return fail");
        if (StringUtils.isBlank(message)) {
            message = ResultEnum.ERROR.getMessage();
        }
        return Result.builder()
                .code(code)
                .message(message)
                .login(Objects.nonNull(RequestContextHolder.getRequestContext()) && RequestContextHolder.getRequestContext().isLogin())
                .build();
    }
}
